package org.javaforever.cookieshop.shiro;

import java.util.HashSet;
import java.util.Set;
import java.util.ArrayList;
import java.util.List;

import jakarta.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import org.javaforever.cookieshop.domain.UserBean;
import org.javaforever.cookieshop.service.UserService;
import org.javaforever.cookieshop.domain.RoleBean;
import org.javaforever.cookieshop.service.RoleService;
import org.javaforever.cookieshop.domain.PermissionBean;

public class UserRealm extends AuthorizingRealm
{
    @Autowired
    private UserService userService;

    @Autowired
    private RoleService roleService;

    /**
    * 执行认证逻辑
    * @param authenticationToken
    * @return
    * @throws AuthenticationException
    */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException
    {
        try {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken; //获得用户输入的用户名,这个对象就是login()传递过来的，将它强转以取出封装的用户名
        String userNameInput = token.getUsername();

        UserBean selectUser = userService.findUserByUserName(userNameInput);
        String encPassowrd = userService.getPasswordUser(userNameInput);
        if(selectUser == null || selectUser.getActive() == false) //用户不存在，返回null
        {
            return null;
        }

        return new SimpleAuthenticationInfo(selectUser, encPassowrd, "");
        }catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException();
        }
    }

    /**
    * 执行授权逻辑
    * @param principalCollection
    * @return
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)
    {
        try {
            Subject subject = SecurityUtils.getSubject(); //获得一个Subject对象
            UserBean user = (UserBean) subject.getPrincipal(); //获得登录的对象
            Set<String> roleNames=new HashSet<String>();
            List<String> permissionNameList=new ArrayList<String>();
            
            Set<RoleBean> roles = userService.listActiveUserRolesUsingUserId(user.getId());
            for(RoleBean role:roles){
                roleNames.add(role.getRoleName());
                Set<PermissionBean> permissions = roleService.listActiveRolePermissionsUsingRoleId(role.getId());
                for (PermissionBean permission: permissions) {
                    permissionNameList.add(permission.getPermName());
                }
            }
    
            if(roleNames==null || roleNames.isEmpty())
            {
                roleNames.add("noAnyAuth");
            }
            
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); //创建一个这样的对象，它是返回的类型的子类
            info.setRoles(roleNames);
            info.addStringPermissions(permissionNameList);

            return info;
        } catch (Exception e) {
            return null;
        }
    }
}
